﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using System.Reflection;
using Microsoft.Xna.Framework.Content;
using DARE.Save.DataStructures;

namespace DARE
{
    public class CGameObjectData: ISaveData
    {
        [ContentSerializer]
        public CGameObject gameObject;
        [ContentSerializer]
        public List<CComponentData> components;
        public string node;

        /// <summary>
        /// Fills this data structure with everything usefull to recreate the object as he is.
        /// </summary>
        /// <param name="go"></param>
        public virtual void FillDataStructure(object gamobj)
        {
            CGameObject go = gamobj as CGameObject;
            if (go.Node != null)
                node = go.Node.Name;
            gameObject = go;
            components = new List<CComponentData>();
            foreach (CComponent c in go.GetComponentList())
            {
                AttrTypeDependentSerializable att = c.GetType().GetCustomAttributes(typeof(AttrTypeDependentSerializable), false).First() as AttrTypeDependentSerializable;
                Type t = att.TypeOfDataStructure;
                if (t == null)
                    t = typeof(CGameObjectData);
                CComponentData cdata = (CComponentData)t.GetConstructor(new Type[0]).Invoke(new object[0]);
               

                cdata.FillDataStructure(c);
                cdata.gameObjectId = go.ID;
                components.Add(cdata);
            }
            
        }

        public virtual void FillFromDataStructure(out object gamo, params object[] paramsData)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Fills the object with its saved values.
        /// </summary>
        /// <param name="go"></param>
        public virtual void FillFromDataStructure(ref CGameObject go, CRender3D render, CHUDSystem hud)
        {
            if (node != null)
                go.Node = render.GetNode(node);


            foreach (CComponentData compData in components)
            {
                compData.component.GameObject = go;
                compData.FillFromDataStructure(ref compData.component, render, hud);
            }
            if (go != null)
            {
                go.ID = gameObject.ID;
                go.IsInitialized = false;
            }
        }

    }
}
